<?php
namespace App\Http\Classes;
use Illuminate\Support\Facades\DB;

/**
 * Created by PhpStorm.
 * User: Celebration-Grey
 * Date: 2017/4/12
 * Time: 15:05
 */
class User
{
    public $user_id;
    private $db;
    public function __construct($userId)
    {
        $this -> user_id = $userId;
        $this -> connect();
    }

    private function connect(){
        $this -> db = DB::table('weibo_users') -> where('user_id','=',$this->user_id);
    }

    private function disConnect(){
        unset($this -> db);
    }

    public function getSelfInfo(){
        $users = $this->db->select(
            'user_id',
            'user_nickname',
            'user_level',
            'user_head_img',
            'user_sex',
            'user_info',
            'user_bg_img',
            'user_bowen_count',
            'user_following_count',
            'user_followed_count',
            'user_card_img',
            'user_card_img_big',
            'user_head_img_big',
            'user_email',
            'user_name',
            'user_tencent',
            'user_phone',
            'user_blog',
            'user_address',
            'user_work',
            'user_school',
            'user_datetime',
            'user_birthday',
            'user_point',
            'user_city',
            'user_province',
            'user_bloodtype',
            'user_sex_orientation',
            'user_sentiment'
        )->get();
        if($users){
            return $users[0];
        }
        else{
            return null;
        }
    }

    public function updateSelfInfo($data){
        //var_dump($data);
        if(isset($data['user_nickname'])
            && isset($data['user_name'])
            && isset($data['user_sex'])
            && isset($data['user_province'])
            && isset($data['user_city'])
            && isset($data['user_bloodtype'])
            && isset($data['user_sentiment'])
            && isset($data['user_sex_orientation'])
            && isset($data['user_blog'])
            && isset($data['user_work'])
            && isset($data['user_school'])
            && isset($data['user_phone'])
            && isset($data['user_tencent'])
            && isset($data['user_info'])
            && isset($data['user_birthday']))
        {
            //echo '参数正确';
            $user = $this -> db -> update([
                'user_nickname' => $data['user_nickname'],
                'user_name' => $data['user_name'],
                'user_sex' => $data['user_sex'],
                'user_city' => $data['user_city'],
                'user_province' => $data['user_province'],
                'user_bloodtype' => $data['user_bloodtype'],
                'user_sentiment' => $data['user_sentiment'],
                'user_sex_orientation' => $data['user_sex_orientation'],
                'user_blog' => $data['user_blog'],
                'user_work' => $data['user_work'],
                'user_school' => $data['user_school'],
                'user_phone' => $data['user_phone'],
                'user_tencent' => $data['user_tencent'],
                'user_info' => $data['user_info'],
                'user_birthday' => $data['user_birthday']
            ]);
            if($user){
                $user = $this->getSelfInfo();
                if($user){
                    return $user;
                }
                else{
                    return null;
                }
            }
            else{
                return false;
            }
        }
        else{
            return false;
        }
    }

    public function getUidInfo(){
        $users = $this->db->select(
            'user_id',
            'user_nickname',
            'user_level',
            'user_head_img',
            'user_sex',
            'user_info',
            'user_bg_img',
            'user_bowen_count',
            'user_following_count',
            'user_followed_count',
            'user_card_img',
            'user_card_img_big',
            'user_head_img_big'
        )->get();
        if($users){
            return $users[0];
        }
        else{
            return null;
        }
    }

    public function updateHead($path_m,$path_b,$path_s){
        $users = $this->db->update([
            'user_head_img' => $path_m,
            'user_head_img_big' => $path_b,
            'user_head_img_small' => $path_s
        ]);
        if($users){
            return true;
        }
        else{
            return false;
        }
    }

    public function updateCover($path_m,$path_b,$path_s){
        $users = $this->db->update([
            'user_card_img' => $path_m,
            'user_card_img_big' => $path_b,
            'user_card_img_small' => $path_s
        ]);
        if($users){
            return true;
        }
        else{
            return false;
        }
    }

    public function updateBackground($path){
        $users = $this->db->update([
            'user_bg_img' => $path
        ]);
        if($users){
            return true;
        }
        else{
            return false;
        }
    }

    public static function selectSimple($userId){
        $users = DB::table('weibo_users')->where('user_id','=',$userId)->select(
            'user_id',
            'user_nickname',
            'user_level',
            'user_head_img'
        )->get();
        return $users[0];
    }

    public static function login($email,$password){
        $users = DB::table("weibo_users");
        $hash_password = hash('md5',$password);
        $result = $users->where('user_email','=',$email)->where('user_password','=',$hash_password)->select('user_id')->get();
        if ($result){
            $token = hash('md5',Common::getRand());
            $users->where('user_id','=',$result[0]->user_id)->update(['user_token' => $token]);
            setcookie('user_token',$token,time()+3600*24*7,'/');
            setcookie('user_id',$result[0]->user_id,time()+3600*24*7,'/');
            return $token;
        }else{
            setcookie("user_token", "", time()-3600,'/');
            setcookie('user_id','',time()-3600,'/');
            return false;
        }
    }

    public static function insert($dataArray){
        $data = [];
        $users = DB::table('weibo_users');
        $data['user_nickname'] = $dataArray['user_nickname'];
        $data['user_email'] = $dataArray['user_email'];
        $data['user_password'] = hash('md5',$dataArray['user_password'].$dataArray['user_email']);
        $data['user_token'] = hash('md5',Common::getRand().$data['user_email']);
        $result = $users->where('user_token','=', $data['user_token'])->count();
        if($result){
            User::insert($dataArray);
        }
        else{
            $users = $users->insertGetId($data);
            if($users){
                setcookie('user_token',$data['user_token'],time()+3600*24*7,'/');
                setcookie('user_id',$users,time()-3600,'/');
                $result = array();
                $result['user_id'] = $users;
                $result['user_token'] = $data['user_token'];
                $result['user_nickname'] = $data['user_nickname'];
                $result['user_head_img'] = 'http://i1.hdslb.com/bfs/face/c6a5972c0b0a1b1b6d59a728ab91593bde00cdbd.jpg';
                return $result;
            }
            else{
                setcookie("user_token", "", time()-3600,'/');
                setcookie('user_id','',time()-3600,'/');
                return false;
            }
        }
        return false;
    }

    public static function passwordVerifiy($email,$password){
        $users = DB::table("weibo_users");
        $hash_password = hash('md5',$password.$email);
        $token = null;
        $result = $users->where('user_email','=',$email)->where('user_password','=',$hash_password)->select(
            'user_id',
            'user_nickname',
            'user_head_img',
            'user_card_img',
            'user_bg_img',
            'user_sex',
            'user_bowen_count',
            'user_followed_count',
            'user_following_count',
            'user_level',
            'user_email',
            'user_token'
        )->get();
        $data = array();
        if ($result){
            $token = hash('md5',Common::getRand());
            $users->where('user_id','=',$result[0]->user_id)->update(['user_token' => $token]);
            setcookie('user_token',$token,time()+3600*24*7,'/');
            setcookie('user_id',$result[0]->user_id,time()+3600*24*7,'/');
            $result[0]->user_token = $token;
            $data['info'] = $result[0];
            $data['token'] = $token;
            return $data;
        }else{
            setcookie("user_token", "", time()-3600,'/');
            setcookie('user_id','',time()-3600,'/');
            return null;
        }
        //return $token;
    }

    public static function updatePassword($email,$newPassword){
        $newPassword = hash('md5',$newPassword.$email);
        $user = DB::table('weibo_users');
        $result = $user->where('user_email','=',$email)->update(['user_password' => $newPassword]);
        if($result){
            return true;
        }
        else{
            return false;
        }
    }

    public static function mysqlTokenVerifiy($id,$token){
        $users = DB::table('weibo_users');
        $result = $users->where('user_token', '=', $token)->select(
            'user_id',
            'user_nickname',
            'user_head_img',
            'user_card_img',
            'user_bg_img',
            'user_sex',
            'user_bowen_count',
            'user_followed_count',
            'user_following_count',
            'user_level',
            'user_email',
            'user_token'
        )->get();
        if($result){
            $data = [];
            $data['info'] = $result[0];
            $data['token'] = $result[0]->user_token;
            RedisCache::setUserInfo($id,$data);
            return $data;
        }
        else{
            return null;
        }
    }

    public static function redisTokenVerifiy($id,$token){
        if(RedisCache::isUserExists($id)){
            $info = RedisCache::getUserInfo($id);
            //$info = json_decode($info);
            //var_dump($info);
            if($token == $info->token){
                return $info;
            }
            else{
                return null;
            }
        }
        else{
            return null;
        }
    }

//    public static function accessTokenVerifly($id,$token){
//        $users = DB::table('weibo_users');
//        $result = $users->where('user_token','=',$token)->where('user_id','=',$id)->count();
//        if($result){
//            return true;
//        }
//        else{
//            return false;
//        }
//    }

    public static function accessTokenVerifly($id,$token){
        if(RedisCache::isUserExists($id)){
            $rtoken = RedisCache::getUserInfo($id);
//            var_dump($rtoken);
            //$rtoken = json_decode($rtoken);
            if($token == $rtoken->token){
                return true;
            }
            else{
                return false;
            }
        }
        else{
            return false;
        }
    }

    public static function logOut(){
        setcookie("user_token", "", time()-3600,'/');
        setcookie('user_id','',time()-3600,'/');
        return true;
    }

    public static function isEmail($email){
        $pattern = "/^[_a-zA-Z0-9\-\.]+@([\-_a-zA-Z0-9]+\.)+[a-zA-Z0-9]{2,3}$/";
        if(preg_match($pattern,$email)){
            return true;
        }
        else{
            return false;
        }
    }

    public static function isPassword($password){
        $pattern = "/\w{6,18}$/";
        if(preg_match($pattern,$password)){
            return true;
        }
        else{
            return false;
        }
    }

    public static function isNickName($nickname){
        $pattern = "/[@#\$%\^&\*]+/";
        if (preg_match($pattern,$nickname)){
            return false;
        }
        else{
            return true;
        }
    }

    public static function isNicknameExist($nickname){
        $users = DB::table('weibo_users');
        $users = $users->where('user_nickname','=',$nickname)->count();
        if($users){
            return true;
        }
        else{
            return false;
        }
    }

    public static function isEmailExist($email){
        $users = DB::table('weibo_users');
        $users = $users->where('user_email', '=', $email)->count();
        if($users){
            return true;
        }
        else{
            return false;
        }
    }

    public static function selectUser($data){
        $user = DB::table('weibo_users');
        $count = $user -> count();
        if(isset($data['orderBy'])){
            if(isset($data['order'])){
                if($data['orderBy'] == 'id'){
                    $user = $user -> orderBy('user_id',$data['order']);
                }
                else if($data['orderBy'] == 'followed'){
                    $user = $user -> orderBy('user_followed_count',$data['order']);
                }
                else if($data['orderBy'] == 'following'){
                    $user = $user -> orderBy('user_following_count',$data['order']);
                }
                else if($data['orderBy'] == 'bowen'){
                    $user = $user -> orderBy('user_bowen_count',$data['order']);
                }
                else {
                    $user = $user -> orderBy('user_id',$data['order']);
                }
            }
            else{
                if($data['orderBy'] == 'id'){
                    $user = $user -> orderBy('user_id','asc');
                }
                else if($data['orderBy'] == 'followed'){
                    $user = $user -> orderBy('user_followed_count','asc');
                }
                else if($data['orderBy'] == 'following'){
                    $user = $user -> orderBy('user_following_count','asc');
                }
                else if($data['orderBy'] == 'bowen'){
                    $user = $user -> orderBy('user_bowen_count','asc');
                }
                else {
                    $user = $user -> orderBy('user_id','asc');
                }
            }
        }
        else{
            $user = $user -> orderBy('user_id','asc');
        }

        if(isset($data['index']) && isset($data['limit'])){
            $user = $user -> skip(($data['index'] - 1) * $data['limit']) -> take($data['limit']);
        }
        else if(isset($data['limit'])){
            $user = $user -> skip(1) -> take($data['limit']);
        }
        else{
            $user = $user -> skip(1) -> take(20);
        }

        $user = $user->get();
        if($user){
            $result = [];
            $result['total'] = $count;
            $result['users'] = $user;
            return $result;
        }
        else{
            return null;
        }
    }

    public function getInfo(){
        $result = $this -> db -> get();
        if($result){
            return $result[0];
        }
        else{
            return null;
        }
    }
}